import pytest
from app.main import app
from httpx import AsyncClient, ASGITransport
from app.core.config import settings
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from app.core.session import get_db
from app.core.logger import init_logger, attach_sql_logger

# 初始化测试日志
init_logger("test")

test_engine = create_async_engine(str(settings.DATABASE_URL), echo=True)
attach_sql_logger(test_engine.sync_engine, "test")

async_db_session = sessionmaker(
    test_engine, class_=AsyncSession, expire_on_commit=False
)

@pytest.fixture
async def db_session() -> AsyncSession:
    """提供一个新的 Session，每个测试函数独立"""
    async with async_db_session() as session:
        yield session

# 覆盖 FastAPI 里的 get_db 依赖，让接口用测试 Session
@pytest.fixture(autouse=True)
async def override_get_db(db_session: AsyncSession):
    async def _get_test_db():
        yield db_session
    app.dependency_overrides[get_db] = _get_test_db
    yield
    app.dependency_overrides.clear()

@pytest.fixture(scope="module")
async def client():
    """提供一个 httpx AsyncClient 用于测试 API"""
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as c:
        yield c